package IO;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
//案例1，查找到一个文件并确定是否要删除
public class Demo11 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的目录");
        String Rootdirpath = scanner.next();
        System.out.println("请输入要删除的文件");
        String toDeleteName = scanner.next();
        File rootDir = new File(Rootdirpath);
        if(!rootDir.isDirectory()) {   //判断是否是目录
            System.out.println("输入的扫描目录有误");
            return;
        }
        scanDir(rootDir,toDeleteName);
    }
    public static void scanDir(File rootDir,String toDeleteName) {
        File[] files = rootDir.listFiles();
        if(files == null) {
            return;
        }
        for (File file:files) {
            if(file.isFile()){  //如果是普通文件
                if(file.getName().contains(toDeleteName)){  //如果包含关键字
                    deleteFile(file);
                }
            }else if(file.isDirectory()) {   //如果是目录
                scanDir(file,toDeleteName);
            }
        }
    }
    public static void deleteFile(File file){
        try {
            System.out.println(file.getCanonicalFile()+"确定要删除吗?(y/n)");
            Scanner scanner = new Scanner(System.in);
            String choice = scanner.next();
            if(choice.equals("y") || choice.equals("Y")) {
                file.delete();
                System.out.println("文件删除成功");
            }else {
                System.out.println("文件取消删除");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
